package com.gues.controller.admin;

import com.gues.eneity.Article;
import com.gues.eneity.Tag;
import com.gues.eneity.Time;
import com.gues.eneity.User;
import com.gues.service.AdminService;
import com.gues.utils.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/admin")
public class AdminController {

    @Resource
    AdminService adminService;

    // 上传图片
    @PostMapping("/upload")
    public @ResponseBody String upload(MultipartFile file) {
        //        String folder = "/www/server/tomcat/webapps/photo/static/";
        String folder = "C:\\Users\\dell\\Desktop";
        File imageFolder = new File(folder);
        File f = new File(imageFolder, file.getOriginalFilename());
        if (!f.getParentFile().exists())
            f.getParentFile().mkdirs();
        try {
            file.transferTo(f);
            String imgURL = "http://localhost:9090/img/" + f.getName();
            return imgURL;
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

    @PostMapping("/submit")
    public @ResponseBody Map<String, Object> submit(@RequestBody Article article) {
        Map<String, Object> map = new HashMap<>();
        int result = adminService.insert(article);
        if ( result != 0) {
            map.put("code", 200);
            map.put("msg", "数据插入成功");
        } else {
            map.put("code", 401);
            map.put("msg", "数据插入失败");
        }
        return map;
    }

    @GetMapping("/selectList")
    public @ResponseBody List<Article> selectList() {
        return adminService.selectList();
    }

    @GetMapping("/delete")
    public @ResponseBody Map<String, Object> deleteById(Integer id) {
        Map<String, Object> map = new HashMap<>();
        int result = adminService.deleteById(id);
        if ( result != 0) {
            map.put("code", 200);
            map.put("msg", "删除成功");
        } else {
            map.put("code", 401);
            map.put("msg", "删除失败");
        }
        return map;
    }

    @PostMapping("/insertTime")
    public @ResponseBody Map<String, Object> insertTime(@RequestBody Time time) {
        Map<String, Object> map = new HashMap<>();
        System.out.println(time);
        int result = adminService.insertTime(time);
        if ( result != 0) {
            map.put("code", 200);
            map.put("msg", "插入时间线成功");
        } else {
            map.put("code", 401);
            map.put("msg", "插入时间线失败");
        }
        return map;
    }

    @RequestMapping("/test")
    public @ResponseBody String test( ) {
        return "success";
    }

}
